package model

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"github.com/jmoiron/sqlx"
	"zimuzu_cvn_web_api/config"
	"zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
)

type ShopOrder struct {
	OID           int64   `db:"oid" json:"oid"`
	OrderNo       string  `db:"order_no" json:"order_no"`
	CreateTime    string  `db:"create_time" json:"create_time"`
	UID           int64   `db:"uid" json:"uid"`
	NickName      string  `db:"nickname" json:"nickname"`
	Phone         string  `db:"phone" json:"phone"`
	Num           int     `db:"num" json:"num"`
	Type          int     `db:"type" json:"type"`
	Money         float64 `db:"money" json:"money"`
	PayWalletAddr string  `db:"pay_wallet_addr" json:"pay_wallet_addr"`
	Status        int     `db:"status" json:"status"`
	Address       string  `db:"address" json:"address"`
	ExpressNo     string  `db:"express_no" json:"express_no"`
	TradeSha      string  `db:"trade_sha" json:"trade_sha"`
}

type ShopOrderListParams struct {
	PageParams
	Status        int    `form:"status"`
	TargetUid     int    `form:"targetUid"`
	OrderNo       string `form:"order_no"`
	PayWalletAddr string `form:"pay_wallet_addr"`
	TradeSha      string `form:"trade_sha"`
	Phone         string `form:"phone"`
	Username      string `form:"username"`
}

// 获取订单信息
func ListShopOrder(params ShopOrderListParams) (res []ShopOrder, err error) {
	start := (params.Page - 1) * params.Per
	sqlStr := "SELECT oid, order_no, FROM_UNIXTIME(create_time, '%Y/%m/%d %H:%i:%s') AS create_time, uid, nickname, phone, num," +
		" `type`, money, IFNULL(pay_wallet_addr, '') AS pay_wallet_addr, address, `status`, address, IFNULL(express_no, '') AS express_no, IFNULL(trade_sha, '') AS trade_sha FROM shop_order WHERE 1 "
	if params.Status >= 0 {
		sqlStr += fmt.Sprintf("AND `status` = %d ", params.Status)
	}
	if params.TargetUid > 0 {
		sqlStr += fmt.Sprintf("AND `uid` = %d ", params.TargetUid)
	}
	if len(params.OrderNo) > 0 {
		sqlStr += fmt.Sprintf("AND `order_no` = '%s' ", params.OrderNo)
	}
	if len(params.PayWalletAddr) > 0 {
		sqlStr += fmt.Sprintf("AND `pay_wallet_addr` = '%s' ", params.PayWalletAddr)
	}
	if len(params.TradeSha) > 0 {
		sqlStr += fmt.Sprintf("AND `trade_sha` = '%s' ", params.TradeSha)
	}
	if len(params.Phone) > 0 {
		sqlStr += fmt.Sprintf("AND `phone` = '%s' ", params.Phone)
	}
	if len(params.Username) > 0 {
		sqlStr += fmt.Sprintf("AND `nickname` = '%s' ", params.Username)
	}
	sqlStr += fmt.Sprintf("ORDER BY oid DESC LIMIT %d,%d ", start, params.Per)

	err = sqlx.Select(config.C.DB.DB, &res, sqlStr)
	if err != nil {
		e.Log("err", err.Error())
		return
	}
	return
}

func GetShopOrderCount(params ShopOrderListParams) (int, error) {
	var count sql.NullInt64
	sqlStr := "select count(*) from shop_order where 1 "
	if params.Status >= 0 {
		sqlStr += fmt.Sprintf("AND `status` = %d ", params.Status)
	}
	if params.TargetUid > 0 {
		sqlStr += fmt.Sprintf("AND `uid` = %d ", params.TargetUid)
	}
	if len(params.OrderNo) > 0 {
		sqlStr += fmt.Sprintf("AND `order_no` = '%s' ", params.OrderNo)
	}
	if len(params.PayWalletAddr) > 0 {
		sqlStr += fmt.Sprintf("AND `pay_wallet_addr` = '%s' ", params.PayWalletAddr)
	}
	if len(params.TradeSha) > 0 {
		sqlStr += fmt.Sprintf("AND `trade_sha` = '%s' ", params.TradeSha)
	}
	if len(params.Phone) > 0 {
		sqlStr += fmt.Sprintf("AND `phone` = '%s' ", params.Phone)
	}
	if len(params.Username) > 0 {
		sqlStr += fmt.Sprintf("AND `nickname` = '%s' ", params.Username)
	}
	err := sqlx.Get(config.C.DB.DB, &count, sqlStr)
	if err != nil {
		e.Log("err", "GetShopOrderCount 失败", err.Error())
	}
	return e.Int64ToInt(count.Int64), err
}

type EditShopOrderParams struct {
	Oid           int    `form:"oid" binding:"required"`
	Status        int    `form:"status"`
	Name          string `form:"name" binding:"required"`
	Area          int    `form:"area" binding:"required"`
	Phone         int    `form:"phone" binding:"required"`
	PostCode      int    `form:"post_code" binding:"required"`
	Address       string `form:"address" binding:"required"`
	ExpressNo     string `form:"express_no"`
	TradeSha      string `form:"trade_sha"`
	PayWalletAddr string `form:"pay_wallet_addr"`
}

func EditShopOrder(params EditShopOrderParams) (err error) {
	//{"name":"aa","area":"86","phone":"15327215133","post_code":"123123","address":"123"}
	address := map[string]interface{}{
		"name":      params.Name,
		"area":      params.Area,
		"phone":     params.Phone,
		"post_code": params.PostCode,
		"address":   params.Address,
	}
	addressStr, _ := json.Marshal(address)

	sqlStr := fmt.Sprintf("UPDATE shop_order SET `address` = '%s'", string(addressStr))
	if len(params.ExpressNo) > 0 {
		sqlStr += fmt.Sprintf(", `express_no` = '%s'", params.ExpressNo)
	}
	if len(params.TradeSha) > 0 {
		sqlStr += fmt.Sprintf(", `trade_sha` = '%s'", params.TradeSha)
	}
	if params.Status > 0 {
		sqlStr += fmt.Sprintf(", `status` = '%d'", params.Status)
	}
	sqlStr += fmt.Sprintf(" where oid = %d", params.Oid)

	res := sqlx.MustExec(config.C.DB.DB, sqlStr)
	_, err = res.RowsAffected()
	if err != nil {
		e.Log("err", err.Error())
		return errno.DbError
	}
	return
}
